package logic

import (
	"context"
	"encoding/json"
	"errors"
	"strconv"
	"time"
	"user-item/models/cache"
	"user-item/models/mysql"

	"user-item/userrpc/internal/svc"
	"user-item/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsAddLogic {
	return &GoodsAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 添加商品
func (l *GoodsAddLogic) GoodsAdd(in *userrpc.GoodsAddRequest) (*userrpc.GoodsAddResponse, error) {
	// todo: add your logic here and delete this line

	goods := mysql.Goods{
		GoodsName:  in.GoodsName,
		GoodsPrice: in.GoodsPrice,
		GoodsImage: in.GoodsImage,
		Stock:      in.Stock,
		UserId:     in.UserId,
	}
	key := "goods_" + strconv.Itoa(int(in.UserId))
	if err := goods.GoodsAdd(mysql.DB); err != nil {
		return nil, errors.New("商品添加失败")
	}
	jsonGoods, _ := json.Marshal(goods)
	cache.Rdb.Set(l.ctx, key, jsonGoods, time.Hour*2)

	return &userrpc.GoodsAddResponse{
		GoodsId: int64(int(goods.ID)),
	}, nil
}
